/**
 * 数据库模型导出
 */

'use strict';

const fs = require('fs');
const path = require('path');
const Sequelize = require('sequelize');
const process = require('process');
const basename = path.basename(__filename);
const env = process.env.NODE_ENV || 'development';
const config = require('../config/database.js')[env];
const db = {};
const logger = require('../utils/logger');

let sequelize;
try {
  if (config.use_env_variable) {
    sequelize = new Sequelize(process.env[config.use_env_variable], config);
  } else {
    sequelize = new Sequelize(config.database, config.username, config.password, config);
  }
  logger.info('Sequelize连接已初始化');
} catch (error) {
  logger.error('Sequelize连接初始化失败:', error);
  // 使用SQLite作为备用
  sequelize = new Sequelize({
    dialect: 'sqlite',
    storage: ':memory:',
    logging: false
  });
  logger.info('使用内存SQLite作为备用数据库');
}

// 定义所有需要加载的模型
const modelsToLoad = [
  { name: 'User', path: './user', isSequelize: true },
  { name: 'Setting', path: './setting', isSequelize: false }, // MongoDB模型
  { name: 'PhoneBlacklist', path: './phoneBlacklist', isSequelize: true },
  { name: 'ContentBlacklist', path: './contentBlacklist', isSequelize: true },
  { name: 'WhatsappSession', path: './whatsappSession', isSequelize: true },
  { name: 'Contact', path: './contact', isSequelize: true },
  { name: 'CrmCustomer', path: './crmCustomer', isSequelize: true },
  { name: 'Message', path: './message', isSequelize: true },
  { name: 'PresetFile', path: './presetFile', isSequelize: true },
  { name: 'ActivityLog', path: './activityLog', isSequelize: true },
  { name: 'UserActivity', path: './UserActivity', isSequelize: true },
  { name: 'UserSession', path: './UserSession', isSequelize: true },
  { name: 'CustomerData', path: './CustomerData', isSequelize: true }
];

// 第一步：加载所有模型
modelsToLoad.forEach(({ name, path: modelPath, isSequelize }) => {
  try {
    const fullPath = require.resolve(modelPath);
    if (isSequelize) {
      db[name] = require(fullPath)(sequelize, Sequelize.DataTypes);
    } else {
      db[name] = require(fullPath); // MongoDB等其他模型直接导入
    }
    logger.info(`${name}模型已加载`);
  } catch (error) {
    // 模型文件不存在是正常的，只记录警告
    logger.warn(`${name}模型不存在或加载失败:`, error.message);
  }
});

// 第二步：建立所有模型的关联关系
Object.keys(db).forEach(modelName => {
  if (db[modelName] && typeof db[modelName].associate === 'function') {
    try {
      db[modelName].associate(db);
      logger.info(`${modelName}模型关联已建立`);
    } catch (error) {
      logger.error(`建立${modelName}模型关联失败:`, error);
    }
  }
});

db.sequelize = sequelize;
db.Sequelize = Sequelize;

module.exports = db; 